var AldeasInfantiles = angular.module("AldeasInfantiles", []);

AldeasInfantiles.controller("Login", function($scope, $http, $location) {

  $scope.countries = [];
  $scope.hiddenClass = "hidden";
  $scope.errorMessage = "";
  $scope.selectedCountry = 0;
  $scope.$login = {};

  $scope.requestCountries = function () {
    //console.log(currentPath);
    $http({
            async: false,
            method: 'POST', 
            url: currentPath + 'countries/returncountries/'
        }).
        success(function(data) {
          $scope.countries = data;
          $scope.selectedCountry = data[0].id_pais;
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };

  $scope.getParams = function ($login) {
    $params = $.param({
      'loginuser': $login.loginuser,
      'loginpassword': $login.loginpassword,
      'logincountry': $scope.selectedCountry
    })
    $scope.doLogin($params);
  };

  $scope.doLogin = function ($params) {
    $http({
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            url: currentPath + 'users/dologin/',
            method: 'POST', 
            data: $params 
        }).
        success(function(data, status) {
          if(data.response == "success"){
            $scope.errorMessage = "";
            $scope.hiddenClass = "hidden";
            window.location.href = currentPath + 'home/';
          }else if(data.response == "incomplete_form"){
            $scope.hiddenClass = "";
            $scope.errorMessage = "Debes escribir todos los datos del formulario.";
            $timeout(countUp, 5000);
          }else if(data.response == "failed"){
            $scope.hiddenClass = "";
            $scope.errorMessage = "Los datos introducidos son incorrectos, intentalo de nuevo.";
            $timeout(countUp, 5000);
          }
        }).
        error(function(data, status) {
          $scope.hiddenClass = "";
          $scope.errorMessage = data;
        });
  };

  var countUp = function() {
    $scope.hiddenClass = "hidden";
  }

  $scope.requestCountries(); 
  $scope.$login.loginuser = "";
  $scope.$login.loginpassword = "";
});